package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.common.constants.ApBehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.LikesBehaviorDto;
import com.heima.model.behavior.ReadBehaviorDto;
import com.heima.model.behavior.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * create 2023/6/27 20:54
 */


@Service
@Slf4j
public class ApBehaviorServiceImpl implements ApBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 点赞或取消点赞文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        Integer userId = user.getId();
        if (user == null || userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        boolean isValid = checkParam(dto);
        if (!isValid) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.判断是否是点赞，如果点赞则不能再点赞，否则保存点赞记录
        Short operation = dto.getOperation();
        String likeKey = ApBehaviorConstants.LIKES_ARTICLE + dto.getArticleId();
        Object obj = cacheService.hGet(likeKey, userId.toString());
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
        if (operation == 0) {
            if (obj != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已经点赞了！");
            }
            log.info("保存当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
            cacheService.hPut(likeKey, userId.toString(), JSON.toJSONString(dto));
            mess.setAdd(1);
            log.error("=============>>like{}",mess);
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //2.如果是取消点赞，则删除对应的记录
        if (obj == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已经取消点赞了！");
        }
        log.info("删除当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
        cacheService.hDelete(likeKey, userId.toString());
        mess.setAdd(-1);
        log.error("=============>>like{}",mess);
        //发送消息，数据聚合
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        if (dto.getArticleId() == null || dto.getCount() < 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String key = ApBehaviorConstants.READ_ARTICLE + dto.getArticleId();
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null ) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        Integer userID = user.getId();
        String readJson= (String) cacheService.hGet(key, userID.toString());
        if (readJson != null) {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(readJson, ReadBehaviorDto.class);
            readBehaviorDto.setCount((short) (readBehaviorDto.getCount()+1));
            cacheService.hPut(key, userID.toString(), JSON.toJSONString(readBehaviorDto));
        }else {
            cacheService.hPut(key, userID.toString(), JSON.toJSONString(dto));
        }
        //发送消息，数据聚合
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setAdd(1);
        log.error("=============>>read{}",mess);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getType() == 0) {
            log.info("保存当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
            cacheService.hPut(ApBehaviorConstants.UNLIKES_ARTICLE + dto.getArticleId().toString(), user.getId().toString(), JSON.toJSONString(dto));
        } else {
            log.info("删除当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
            cacheService.hDelete(ApBehaviorConstants.UNLIKES_ARTICLE + dto.getArticleId().toString(), user.getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }

    private boolean checkParam(LikesBehaviorDto dto) {

        if (dto == null || dto.getArticleId() == null) {
            return false;
        }

        if (dto.getOperation() < 0 || dto.getOperation() > 1) {
            return false;
        }
        if (dto.getType() < 0 || dto.getType() > 2) {
            return false;
        }
        return true;
    }
}
